package com.wj1c.push.lock;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: Mr.Jiao
 * @date: 2018年09月05日
 */
public class DistributedLock {

    private RedisTemplate template;

    public DistributedLock(RedisTemplate template){
        this.template = template;
    }

    public boolean lock(String key, int times, int sleeptime, int locktime){
        ValueOperations<String, String> operations = template.opsForValue();
        for(int i = 0; i < times; i++){
            if(operations.setIfAbsent(key, UUID.randomUUID().toString())){
                operations.getOperations().expire(key, locktime, TimeUnit.MILLISECONDS);
                return true;
            }
            if(sleeptime > 0) {
                try {
                    Thread.sleep(sleeptime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public boolean lock(String key){
        return this.lock(key, 1, 0, 15000);
    }

    public boolean lock(String key, int locktime){
        return this.lock(key, 1, 0, locktime);
    }

    public boolean lock(String key, int times, int locktime){
        return this.lock(key, times, 200, locktime);
    }

    public boolean release_lock(String key){
        return template.opsForValue().getOperations().delete(key);
    }

}
